/**
 * @(#)ApkSimulatorTimer.java 2017年03月25日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import org.jsbd.boss.common.BaseThread;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.MiguMusicConfigBean;
import org.jsbd.boss.domian.MiguMusicDaylimitBean;
import org.jsbd.boss.domian.MiguMusicRetentAddTimer;
import org.jsbd.boss.service.IMiguMusicDaylimitService;
import org.jsbd.boss.service.IMiguMusicRetentAddTimerService;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 咪咕音乐日限更新定时器
 * 
 * @author <a href="mailto:wangjunbiao@zhexinit.com" >王俊标</a>
 * @version 1.0.0
 */
public class MiguMusicDaylimitTimer extends BaseThread {
	public static final Logger LOGGER = LoggerFactory.getLogger(MiguMusicDaylimitTimer.class);

	@Resource
	private IMiguMusicDaylimitService miguMusicDaylimitService;

	@Resource
	private IMiguMusicRetentAddTimerService miguMusicRetentAddTimerService;

	@Resource
	private RedisClient redisClient;

	@Override
	public void start() {
		LOGGER.warn("migu music daylimit update start");
		try {
			if (redisClient.evalSetNx(CacheKey.MIGU_MUSIC_DAYLIMIT_LOCK_KEY, 6)) {
				List<MiguMusicDaylimitBean> mmdBeans = miguMusicDaylimitService.findDeltaData(50);
				List<MiguMusicConfigBean> mmcBeans = new ArrayList<MiguMusicConfigBean>();
				for (MiguMusicDaylimitBean mmdBean : mmdBeans) {
					String mark = mmdBean.getMark();
					String[] marks = mark.split("_");
					
					MiguMusicConfigBean config = new MiguMusicConfigBean();
					config.setChannelId(marks[0]);
					config.setVersion(marks[1]);
					config.setTotalNum(Long.valueOf(String.valueOf(mmdBean.getDaylimit())));
					mmcBeans.add(config);
				}

				if (!mmcBeans.isEmpty()) {
					miguMusicDaylimitService.updateDaylimit(mmcBeans, mmdBeans);
				}
				
				List<MiguMusicRetentAddTimer> list = miguMusicRetentAddTimerService.getIsDoList();
				for (MiguMusicRetentAddTimer timer : list) {
					miguMusicRetentAddTimerService.updateToConfig(timer);
				}

			}
		} catch (Exception e) {
			LOGGER.error("更新日限异常", e);
		} finally {
			redisClient.remove(CacheKey.MIGU_MUSIC_DAYLIMIT_LOCK_KEY);
		}
	}
}
